const _transform_tool = require("../utils/transform_tool");
const { progress } = require("../utils/display_tool");
const { getLastError, resetError, log } = require("../utils/log_tool");
const { BaseCommand, PROCESS_STATE } = require("./base");
const { formatData } = require("./share_data");

class LoopForeverCommand extends BaseCommand {
    async execute() {
        const data = this.selfData;
        const show_progress = this.selfCfg.show_progress;
        for (let loop_index = 0; true; loop_index++) {
            if (this.globalData.process_state === PROCESS_STATE.BREAK) {
                this.resetProcessState();
                break;
            } else if (
                this.globalData.process_state === PROCESS_STATE.CONTINUE
            ) {
                this.resetProcessState();
            }
            const loop_key = loop_index;
            // 键索引值映射
            if (data.index_mapping) {
                this.shareData[data.index_mapping] = loop_index;
            } else {
                this.shareData.loop_index = loop_index;
            }
            // 键映射
            if (data.key_mapping) {
                this.shareData[data.key_mapping] = loop_key;
            } else {
                this.shareData.loop_key = loop_key;
            }
            if (show_progress) {
                log("");
                progress(loop_index, 0, {
                    desc: `> ${this.selfCfg.title || this.selfCfg.type}`,
                    color: "white",
                });
                log("");
            }
            let commandCfgs = data.commands;
            // 特殊处理字符的情况
            if (typeof commandCfgs === "string") {
                commandCfgs = formatData(commandCfgs);
            }
            // 默认从循环开始执行，增加深度
            await this.exec(commandCfgs, this.depth + 1);
            if (show_progress) {
                if (!getLastError()) {
                    progress(loop_index + 1, 0, {
                        desc: `✔ ${this.selfCfg.title || this.selfCfg.type}`,
                        color: "cyan",
                    });
                } else {
                    progress(loop_index + 1, 0, {
                        desc: `✖ ${this.selfCfg.title || this.selfCfg.type}`,
                        color: "red",
                    });
                }
                log("");
            }
            if (getLastError()) {
                if (this.selfCfg.ignore_error) {
                    resetError(this.selfCfg.ignore_error);
                } else {
                    throw getLastError();
                }
            }
        }
        // 最后一个循环结束后，需要重置掉执行状态
        this.resetProcessState();
    }
}

module.exports = {
    LoopForeverCommand,
};
